<template>
  <div id="cart-view" style="background-color: #F6F7F9; height: 100vh; overflow: auto">
    <van-sticky>
      <div class="cart-title" style="display: block;background-color: #fff; height: 55px; text-align: center; align-content: center; font-size: 18px">
        购物车
        <span @click="showEdit = !showEdit"
              style="position: absolute; right: 16px; color: #FA6408; align-content: center; font-size: 16px"
        >{{ showEdit ? '取消' : '编辑' }}
        </span>
      </div>
    </van-sticky>

    <div id="cart-content" style="margin-top: 15px">
      <van-checkbox-group v-model="checkedItemIndexes" ref="checkboxGroup" checked-color="#FA6408">
        <van-swipe-cell v-for="(cartItem, index) in cartItems" :key="cartItem.cartId"
                        style="margin-bottom: 10px">
          <div class="cart-item-card" style="display: flex; align-items: center;">
            <div class="checkbox" style="display: flex; float: left; width: 50px; justify-content: center">
              <van-checkbox :name="index"></van-checkbox>
            </div>
            <van-card
                class="goods-card"
                :thumb="require('@/'+`${cartItem.product.imageUrl}`)"
            >
              <template #title>
                <span style="font-size: 16px; display: block; margin-bottom: 8px">{{ cartItem.product.productName }}</span>
              </template>
              <template #tags>
                <van-tag plain type="danger" style="font-size: 12px; color: #646566; margin-right: 2px"
                         v-for="typeName in types[index].typeNames" :key="typeName">{{ typeName }}
                </van-tag>
              </template>
              <template #price>
                <span style="color: #FA6408; font-size: 12px" @click="handleClick(cartItem.productId)">
                  ￥
                  <span style="font-size: 20px">{{ cartItem.price * cartItem.quantity }}</span>
                </span>
              </template>
              <template #num>
                <van-stepper v-model="cartItem.quantity" input-width="28px" button-size="28px"
                             @plus="onStepperPlus(cartItem.price, cartItem.quantity, cartItem.cartId)"
                             @minus="onStepperMinus(cartItem.price, cartItem.quantity, cartItem.cartId)"
                             @change="onStepperChange(cartItem.quantity, cartItem.cartId)"/>
              </template>
            </van-card>
          </div>

          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="deleteItems([cartItem.cartId])"/>
          </template>
        </van-swipe-cell>
      </van-checkbox-group>

      <van-submit-bar :price="totalPrice*100" @submit="createOrder" style="bottom: 50px">
        <van-checkbox v-model="checkAllStatus" checked-color="#FA6408">全选</van-checkbox>
        <template #button>
          <van-button round type="danger" style="width: 120px" v-if="showEdit" @click="deleteItems(checkedItemIds)">删除所选</van-button>
          <van-button round color="#FA6408" style="width: 120px" v-else @click="createOrder()">提交订单</van-button>
        </template>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import http from "@/plugins/http";
import cartView from "@/views/common-views/cart-views/CartView.vue";
import {Toast} from "vant";

export default {
  computed: {
    cartView() {
      return cartView
    }
  },
  data() {
    return {
      checkedItemIndexes: [],
      checkAllStatus: false,
      checkedItemIds: [],
      checkedItems: [],
      totalPrice: 0,
      showEdit: false,
      cartItems: [],
      types: [
        {
          typeIds: [],
          typeNames: []
        }
      ]
    };
  },
  methods: {
    handleClick(productId) {
      // 实现导航逻辑
      this.$emit('product-click', productId);
      console.log("商品点击事件触发，商品ID是", productId);

      // 使用程序化导航代替 router-link 的跳转
      this.$router.push({ name: 'PetView', params: { id: productId } });
    },
    // 获取当前用户所有订单商品
    getCartItems() {
      let username = sessionStorage.getItem("username").replace(/"/g, '');
      http.get(`/cart/${username}`)
          .then(response => {
            this.cartItems = response.data || [];
            console.log(this.cartItems)
            this.setTypeIds();
          })
          .catch(error => {
            console.error("获取购物车信息出错", error);
          });
    },

    // 设置类型
    setTypeIds() {
      this.cartItems.forEach((item, index) => {
        this.types[index] = {
          typeIds: item.type.split(''),
          typeNames: item.typeNames.split(' ')
        };
      });
    },

    // 全选
    checkAll() {
      this.$refs.checkboxGroup.toggleAll(true);
    },

    // 全不选
    uncheckAll() {
      this.$refs.checkboxGroup.toggleAll(false);
    },

    // 更新选中的购物车商品
    updateCheckedItemIds() {
      this.checkedItemIds = this.checkedItemIndexes.map(index => this.cartItems[index].cartId);
    },

    updateCheckedItems() {
      this.checkedItems = this.checkedItemIndexes.map(index => this.cartItems[index]);
    },

    // 更新购物车总价
    updateTotalPrice() {
      this.totalPrice = this.checkedItemIds.reduce((total, id) => {
        const item = this.cartItems.find(cartItem => cartItem.cartId === id);
        return total + (item.price * item.quantity);
      }, 0);
    },

    // 点击步进器加时的操作
    onStepperPlus(value, quantity, cartId) {
      this.totalPrice += value;
      this.updateItemQuantity(quantity + 1, cartId);
    },

    // 点击步进器减时的操作
    onStepperMinus(value, quantity, cartId) {
      this.totalPrice -= value;
      this.updateItemQuantity(quantity - 1, cartId);
    },

    // 步进器值改变时的操作
    onStepperChange(quantity, cartId) {
      this.updateTotalPrice();
      this.updateItemQuantity(quantity, cartId);
    },

    // 创建订单
    createOrder() {
      /*let username = sessionStorage.getItem("username").replace(/"/g, '');
      const cartIds = this.checkedItems.map(item => item.cartId);
      console.log(cartIds);
      http.post('/order/createByCart', { username:username,cartItemIds:cartIds })
          .then(response => {
            console.log(response)
            if (response.statusCode==='200') {
              Toast.success('订单创建成功！订单号：' + response.data);
              const orderId = response.data; // 假设这里返回的是订单号
              http.get('/items/getById/'+orderId)
                  .then(orderResponse => {
                    if (orderResponse.statusCode === '200') {
                      console.log(orderResponse.data)

                      this.$router.push({
                        name: 'OrderView',
                        params: { orderData: orderResponse.data } // 把订单数据传给 OrderView
                      });
                    } else {
                      Toast.fail('获取订单详情失败，请重试');
                    }
                  })
                  .catch(error => {
                    Toast.fail('获取订单详情失败: ' + error.message);
                  });
              //this.$router.push({ name: 'OrderView', params: { orderData: response.data.order } });
            } else {
              Toast.fail(response.message)
            }
          })*/
      // 判断是否有选中商品
      if (this.checkedItems.length === 0) {
        Toast.fail('未选中任何商品');
        return; // 终止执行
      }

      // 判断选中商品的数量是否超过库存
      for (let item of this.checkedItems) {
        console.log("库存:"+item.product.stock)
        if (item.quantity > item.product.stock) {
          Toast.fail(`商品 "${item.product.productName}" 库存不足`);
          return; // 终止执行
        }
      }
      // 从选中的商品生成数据集
      const orderData = this.checkedItems.map(item => ({
        cartId:item.cartId,
        productName: item.product.productName, // 商品名称
        skuDescription: item.product.description, // 商品描述
        price: item.price, // 商品价格
        quantity: item.quantity, // 商品数量
        imgUrl: require('@/' + item.product.imageUrl), // 图片路径
        stock_num: item.product.stock, // 库存数量
        productId: item.productId, // 商品ID
      }));

      // 打印生成的数据集，方便调试
      console.log("订单数据集:", orderData);

      // 将订单数据传递到 OrderView 页面
      this.$router.push({
        name: 'OrderView',
        params: { orderData }
      });

      console.log("已传递参数:", orderData);
    },

    // 步进器值改变时更新购物车商品数量
    updateItemQuantity(quantity, cartId) {
      http.post('/cart/update', {
        quantity: quantity,
        cartId: cartId
      })
          .then(response => {
            console.log(response);
          })
          .catch(error => {
            console.error("更新购物车商品数量失败:", error);
          });
    },
    deleteItems(cartIds) {
      console.log(cartIds);
      http.post(`/cart/delete`, cartIds)
          .then(response => {
            this.getCartItems();
            console.log(response);
          })
          .catch(error => {
            console.error("删除购物车商品失败", error)
          })
    }
  },
  activated() {
    this.getCartItems();
  },
  watch: {
    checkAllStatus() {
      if (this.checkAllStatus) {
        this.checkAll();
      } else {
        this.uncheckAll();
      }
    },
    checkedItemIndexes() {
      this.updateCheckedItemIds();
      this.updateCheckedItems();
      this.updateTotalPrice();
      this.checkAllStatus = this.checkedItemIndexes.length === this.cartItems.length;
    }
  }
};
</script>

<style scoped>
.cart-item-card {
  background-color: #fff;
}

.goods-card {
  margin: 0;
  background-color: #fff;
  width: 100%;
  padding-left: 0;
}

.delete-button {
  height: 100%;
}
</style>

